package com.ybox.common.email.service.impl;

import com.iotmonitor.common.core.exception.ServiceException;
import com.ybox.common.email.domain.Email;
import com.ybox.common.email.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * Create bySeptember
 * 2019/4/7
 * 21:42
 *
 * @author 16554
 */
@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSenderImpl mailSender;

    final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Email sendMail(Email email) {
        try {
            // 1.检测邮件
            checkMail(email);
            // 2.发送邮件
            sendMimeMail(email);
            // 3.保存邮件
            return saveMail(email);
        } catch (Exception e) {
            email.setStatus("fail");
            email.setError(e.getMessage());
            return email;
        }
    }

    /**
     * 检测邮件信息类
     *
     * @param email
     */
    private void checkMail(Email email) {
        if (StringUtils.isEmpty(email.getReceiverEmail())) {
            throw new ServiceException("邮件收信人id不能为空");
        }
        if (StringUtils.isEmpty(email.getSubject())) {
            throw new ServiceException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(email.getContent())) {
            throw new ServiceException("邮件内容不能为空");
        }
    }

    // 构建复杂邮件信息类
    @Async
    void sendMimeMail(Email email) {
        try {
            // true表示支持复杂类型
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            // 邮件发信人
            messageHelper.setFrom(email.getSenderEmail());
            // 邮件收信人
            messageHelper.setTo(email.getReceiverEmail().split(","));
            // 邮件主题
            messageHelper.setSubject(email.getSubject());
            if (email.getHtml() == null) {
                email.setHtml(false);
            }
            // 邮件内容 参数一：内容 参数二；是否是html
            messageHelper.setText(email.getContent(), email.getHtml());
            // 抄送
            if (!StringUtils.isEmpty(email.getCcEmail())) {
                messageHelper.setCc(email.getCcEmail().split(","));
            }
            // 密送
            if (!StringUtils.isEmpty(email.getBccEmail())) {
                messageHelper.setCc(email.getBccEmail().split(","));
            }
            // 添加邮件附件
            if (email.getMultipartFiles() != null) {
                for (MultipartFile multipartFile : email.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            // 发送时间
            if (StringUtils.isEmpty(email.getSentDate().toString())) {
                email.setSentDate(new Date());
                messageHelper.setSentDate(email.getSentDate());
            }
            // 正式发送邮件
            mailSender.send(messageHelper.getMimeMessage());
            email.setStatus("ok");
        } catch (Exception e) {
            // 发送失败
            logger.error("邮件发送失败！邮件发送人" + email.getSenderEmail() + ",邮件接收" + email.getReceiverEmail() + ",邮件主题:" + email.getSubject() + ",邮件内容:" + email.getContent());
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存邮件
     *
     * @param email
     * @return
     */
    private Email saveMail(Email email) {
        // TODO 将邮件保存到数据库..
        return email;
    }

    /**
     * 获取邮件发信人
     *
     * @return
     */
    @Override
    public String getMailSendFrom() {
        return mailSender.getJavaMailProperties().getProperty("from");
    }

}